
const app = getApp()
Page({
	data: {
		pay: 0,
		number: 0,
		goodsId: 0,
		specificationId: 0,
		acquisitionIndex: null,
		acquisitionId: 0,
		type: 0,
		showPay: false,
		showCoupon: false,
		columns: ['余额支付(免密)', '微信支付'],
		goodsDetail: {},
		discountList: [],
		total: 0,
		discountNum: 0,
		productImg: '',
		productName: '',
		show: false, // 成功弹窗显示
	},
	onLoad: function (options) {
		console.log(options)
		this.getUserMessage()
		if (options.type == 0) {
			this.setData({
				type: options.type,
				specificationId: options.specificationId,
				goodsId: options.id,
			})
			this.getGoodsDetail()
		} else if (options.id) {
			this.setData({
				type: options.type,
				number: options.number,
				goodsId: options.id,
			})
			this.getBoxDetail()
		} else {
			console.log('点击盲盒进来的')
			this.setData({
				type: options.type,
				number: options.number,
				boxId: options.boxId,
				showTotal: options.price,
				total: options.price,
				productImg: options.img,
				productName: (options.name == 'undefined' ? '--' : options.name)
			})
		}
	},
	getUserMessage() {
		let _this = this;
		if (app.globalData.userInfo) {
			this.setData({
				balance: app.globalData.userInfo.balance
			})
		} else {
			app.util.request({
				url: "api/account/selectByOpen_id",
				method: "post",
				success(response) {
					if (response.data.code == 0) {
						app.globalData.userInfo = response.data.data
						_this.setData({
							balance: response.data.data.balance
						})
					}
				}
			})
		}
	},
	getBoxDetail() {
		let _this = this;
		app.util.request({
			url: "api/box/findById",
			method: "post",
			data: {
				id: _this.data.goodsId
			},
			success(response) {
				if (response.data.code == 0) {
					_this.setData({
						goodsDetail: response.data.data,
						showTotal: response.data.data.price * _this.data.number,
						total: response.data.data.price * _this.data.number,
					})
				}
			}
		})
	},
	getGoodsDetail() {
		let _this = this;
		app.util.request({
			url: "api/mall/findById",
			method: "get",
			data: {
				id: _this.data.goodsId,
				specificationId: _this.data.specificationId,
			},
			success(response) {
				if (response.data.code == 0) {
					let chooseSpecification = response.data.data.allSpecification.find(x => x.id == _this.data.specificationId)
					let price = _this.data.specificationId == 0 ? response.data.data.price : chooseSpecification.price
					_this.setData({
						goodsDetail: response.data.data,
						showTotal: price,
						total: price,
					})
				}
			}
		})
	},
	getCouponList() {
		let _this = this;
		_this.setData({
			showCoupon: true
		})
		app.util.request({
			url: "api/acquisition/findUse",
			method: "post",
			data: {
				scene: _this.data.type == 0 ? 1 : 2, //1为直买，2为抽奖(一番赏，盲盒)
				price: _this.data.total
			},
			success(response) {
				if (response.data.code == 0) {
					_this.setData({
						discountList: response.data.data ? response.data.data : []
					})
				}
			}
		})
	},
	onClose() {
		this.setData({
			showCoupon: false
		});
	},
	showPaySheet() {
		this.setData({
			showPay: true
		})
	},
	onChange(e) {
		if (e.type == 'change') {
			this.setData({
				pay: e.detail.index
			})
		} else
			this.setData({
				showPay: false
			})
	},
	toBuy() {
		// type 1 收一盒或全收
		if (this.data.type == 0) {
			console.log(1)
			// return
			this.createBuyGoods()
		} else if (this.data.goodsId) {
			console.log('抽一盒或全收')
			// return
			this.createDrawEtui()
		} else {
			console.log('点击盲盒中某一个进来')
			this.createCurrentDraw()
		}
	},
	chooseDiscount(e) {
		let _this = this;
		let type = e.currentTarget.dataset.item.type;
		let maxPrice = e.currentTarget.dataset.item.discounts.maximum;
		if (type == 4 && parseFloat(_this.data.showTotal) > parseFloat(maxPrice)) {
			wx.showToast({
				title: '对不起，本次交易超出直抽券使用上限!',
				icon: 'none',
				duration: 1500
			})
		} else {
			console.log(e)
			this.setData({
				showCoupon: false,
				acquisitionIndex: e.currentTarget.dataset.index,
				acquisitionId: e.currentTarget.dataset.id
			})
			this.getDiscount()
		}
	},
	payClose() {
		this.setData({
			showPay: false
		})
	},
	getDiscount() {
		let discount = this.data.discountList[this.data.acquisitionIndex]
		if (discount.type == 2) {
			console.log(this.data.showTotal * discount.discounts.discount)
			this.setData({
				discountNum: (this.data.showTotal - (this.data.showTotal * discount.discounts.discount)) > discount.discounts.price ? discount.discounts.price : (this.data.showTotal - (this.data.showTotal * discount.discounts.discount)).toFixed(2)
			})
			this.setData({
				total: (this.data.showTotal - this.data.discountNum).toFixed(2),
				columns: ['余额支付(免密)', '微信支付']
			})
		} else if (discount.type == 4) {
			this.setData({
				total: 0,
				discountNum: this.data.showTotal,
				columns: ['余额支付(免密)']
			})
		} else {
			this.setData({
				total: (this.data.showTotal - discount.discounts.subtract).toFixed(2),
				discountNum: discount.discounts.subtract,
				columns: ['余额支付(免密)', '微信支付']
			})
		}
	},
	createBuyGoods() {
		let query = {}
		let _this = this
		query["pay"] = this.data.pay;
		query["mallId"] = this.data.goodsId;
		if (this.data.specificationId != 0) {
			query["specificationId"] = this.data.specificationId;
		}
		if (this.data.acquisitionId != 0) {
			query["acquisitionId"] = this.data.acquisitionId;
		}
		app.util.request({
			url: "api/orders/add",
			method: "post",
			data: query,
			success(response) {
				if (response.data.code == 200) {
					_this.payorder(response.data.data)
				} else if (response.data.code == 0) {
					wx.showModal({
						title: '提示',
						content: '交易成功',
						showCancel: false,
						success(res) {
							wx.navigateTo({
								url: '/pages/goods/my-goods-index'
							})
						}
					})
				} else if (response.data.code == 402) {
					wx.showToast({
						title: '交易失败，余额不足',
						icon: 'none'
					})
				} else {
					wx.showToast({
						title: '交易失败,请稍后重试',
						icon: 'none'
					})
				}
			}
		})
	},
	createCurrentDraw() {
		let _this = this;
		let query = {}
		query['boxId'] = _this.data.boxId;
		query['pay'] = _this.data.pay;
		if (_this.data.acquisitionId != 0) {
			query['acquisitionId'] = _this.data.acquisitionId
		}
		app.util.request({
			url: 'api/orders/buyetui',
			method: "post",
			data: query,
			success(response) {
				if (response.data.code == 200) {
					_this.payorder(response.data.data)
				} else if (response.data.code == 0) {
					_this.setData({
						show: true
					})
					// wx.showModal({
					// 	title: '提示',
					// 	content: '交易成功',
					// 	showCancel: false,
					// 	success(res) {
					// 		wx.navigateBack({
					// 			delta: 1
					// 		})
					// 	}
					// })
				} else if (response.data.code == 402) {
					wx.showToast({
						title: '余额不足',
						icon: 'none'
					})
				} else {
					wx.showToast({
						title: '交易失败,请稍后重试',
						icon: 'none'
					})
				}
			}
		})
	},
	onKnow() {
		this.setData({
			show: false
		})
		wx.navigateBack({
			delta: 1
		})
	},
	createDrawEtui() {
		let _this = this
		let url = this.data.type == 1 ? 'api/draw/etui' : 'api/draw/postcard'
		let query = {}
		query['boxId'] = this.data.goodsId;
		query['number'] = this.data.number;
		query['pay'] = this.data.pay;
		if (this.data.acquisitionId != 0) {
			query['acquisitionId'] = this.data.acquisitionId
		}
		console.log(query)
		// return
		app.util.request({
			url: url,
			method: "post",
			data: query,
			success(response) {
				if (response.data.code == 200) {
					_this.payorder(response.data.data.orderno)
				} else if (response.data.code == 0) {
					let name = response.data.data.mallName.join(' | ');
					let img = ((response.data.data.img != null && response.data.data.img.length > 0) ? response.data.data.img[0] : '')
					// return
					_this.setData({
						productImg: img,
						productName: name,
						show: true
					})
					// wx.showModal({
					// 	title: '提示',
					// 	content: '交易成功',
					// 	showCancel: false,
					// 	success(res) {
					// 		wx.navigateBack({
					// 			delta: 1
					// 		})
					// 	}
					// })
				} else if (response.data.code == 402) {
					wx.showToast({
						title: '余额不足',
						icon: 'none'
					})
				} else {
					wx.showToast({
						title: '交易失败,请稍后重试',
						icon: 'none'
					})
				}
			}
		})
	},
	payorder(outTradeNo) {
		let _this = this;
		_this.setData({
			loading: true
		})
		let data = {
			outTradeNo: outTradeNo
		};
		app.util.request({
			url: "wxPay/miniAppPay",
			data: data,
			method: "get",
			success(response) {
				let data = response.data.data;
				wx.requestPayment({
					timeStamp: data.timeStamp,
					nonceStr: data.nonceStr,
					package: data.package,
					signType: data.signType,
					paySign: data.paySign,
					appId: data.appId,
					success(res) {
						if (res.errMsg == "requestPayment:ok") {
							wx.showToast({
								title: '支付成功！',
							})
							_this.setData({
								hasPay: true
							})
							setTimeout(() => {
								wx.navigateTo({
									url: '/pages/goods/my-goods-index',
								})
							}, 2000)
						}
					},
					fail(res) {
						console.log(res)
						_this.setData({
							hasPay: false
						})
					}
				})
			},
			complete() {
				_this.setData({
					loading: false
				})
			}
		})
	}
})
